package org.example.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import entity.Article;
import org.example.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import vo.ArticleVo;

/**
 * @author : xuzhennan
 * @Project : 787k-cloud
 * @Package : org.example.controller
 * @email : xuzhennan@58.com
 * @date : 2021年08月29日 上午9:31
 */
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Value("${server.port}")
    public String port;
    @Autowired
    private ArticleService articleService;

    /**
     * 利用 mybatis-plus的分页插件进行分页
     * 如果数据库中记录很多则不建议使用
     *
     * @param pageNumber
     * @param pageSize
     * @return http://localhost:9000/article/findArticlesWithPage?pageNumber=1&pageSize=2
     */
    @RequestMapping("/findArticlesWithPage")
    public ArticleVo findArticlesWithPage(@RequestParam("pageNumber") int pageNumber, @RequestParam("pageSize") int pageSize) {
        IPage<Article> articleWithPage = articleService.findArticlesWithPage(pageNumber, pageSize);
        ArticleVo articleVo = ArticleVo.builder().current(pageNumber).size(pageSize).total(articleWithPage.getTotal())
                .articles(articleWithPage.getRecords()).totalPage(articleWithPage.getPages()).port(port).build();
        return articleVo;
    }


    /**
     * 模拟异常
     *
     * @param id
     * @return http://localhost:9000/article/articleDetail?pageNumber=1&pageSize=2
     */
    int temp = 0;

    @RequestMapping("/articleDetail")
    public Article articleDetail(@RequestParam("id") int id) {
        temp++;
        if (temp % 3 == 0) {
            throw new RuntimeException();
        }
        return articleService.getArticleDetail(id);
    }
}
